package com.song.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.song.common.utils.HttpUtils;
import com.song.mall.member.dao.MemberLevelDao;
import com.song.mall.member.entity.MemberLevelEntity;
import com.song.mall.member.exception.PhoneExistException;
import com.song.mall.member.exception.UserNameExistException;
import com.song.mall.member.vo.MemberLoginVo;
import com.song.mall.member.vo.MemberRegistVo;
import com.song.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.common.utils.PageUtils;
import com.song.common.utils.Query;

import com.song.mall.member.dao.MemberDao;
import com.song.mall.member.entity.MemberEntity;
import com.song.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vos) {
        MemberDao baseMapper = this.baseMapper;
        MemberEntity entity = new MemberEntity();

        //设置默认会员等级
        MemberLevelEntity levelEntity =  memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一
        checkPhoneUnique(vos.getPhone());
        checkUserNameUnique(vos.getUserName());
        entity.setMobile(vos.getPhone());
        entity.setUsername(vos.getUserName());

        entity.setNickname(vos.getUserName());

        //设置密码 进行 MD5加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(vos.getPassword());
        entity.setPassword(password);

        //其他默认信息

        baseMapper.insert(entity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile>0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String username) throws UserNameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer userName = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (userName>0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1、去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity==null){
            //登录失败
            return null;
        }else {
            //拿到数据库的password
            String entityPassword = entity.getPassword();
            //与页面传来的password进行对比
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, entityPassword);
            if (matches){
                //登录成功
                return entity;
            }else {
                return null;
            }
        }
    }


    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        //登录和注册合并逻辑
        //通过vo是得不uid的 uid值没有传进来 为空 所有String uid = vo.getUid();没有用
        //需要提前查出用户的详细信息 在里面获取用户登录唯一id
        Map<String, String> query = new HashMap<>();//用于封装查询参数的
        query.put("access_token", vo.getAccess_token());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSON.parseObject(json);
        String id = jsonObject.getString("id");
        //1、判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", id));
        if (memberEntity != null) {
            //这个用户以及注册了
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            //更新这个令牌
            update.setAccessToken(vo.getAccess_token());
            //更新过期时间
            update.setExpiresIn(vo.getExpires_in());
            memberDao.updateById(update);
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            //重新更新令牌和过期时间
            this.updateById(memberEntity);
            return memberEntity;
        } else { //说明这个用户还没有注册过的
            //没有查到当前社交的用户对应的记录，就需要注册
            MemberEntity regist = new MemberEntity();
            //即使远程查询出现有问题了也没关系，也不用管
            try {
                //查询当前社交用户的社交账号信息（昵称，性别等信息）
                if (response.getStatusLine().getStatusCode() == 200) { //查询成功，有用户的详细数据
                    String name = jsonObject.getString("name");//获取当前微博登录成功后的名称
                    String gender = jsonObject.getString("gender");//获取当前微博登录成功后的性别
                    //设置基本信息
                    regist.setNickname(name); //设置默认的昵称
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {

            }
            //以后只要社交用户是第一次登陆，那么数据库里面就会有一条记录，那么相当于它就是注册进来了
            regist.setSocialUid(id);//设置当前微博登录成功后的Uid
            regist.setAccessToken(vo.getAccess_token());//设置当前登录后的令牌
            regist.setExpiresIn(vo.getExpires_in());//设置当前登录后的令牌过期时间
            //插入数据
            memberDao.insert(regist);
            //插入数据成功以后，说明这个用户也就登陆成功了
            return regist;
        }
    }

}